﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.EnterpriseCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.EnterpriseCommandHandler
{
    /// <summary>
    /// 企业显示命令处理
    /// </summary>
    public class EnterpriseQueryCommandHandler : IRequestHandler<EnterpriseQueryCommand, APIResult<List<Enterprise>>>
    {
        /// <summary>
        /// AutoProfile
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 仓储-企业
        /// </summary>

        private readonly IBaseRepository<Enterprise> enterpriseRepository;

        public EnterpriseQueryCommandHandler(IMapper mapper, IBaseRepository<Enterprise> enterpriseRepository)
        {
            this.mapper = mapper;
            this.enterpriseRepository = enterpriseRepository;
        }

        public async Task<APIResult<List<Enterprise>>> Handle(EnterpriseQueryCommand request, CancellationToken cancellationToken)
        {
            APIPaing<List<Enterprise>> result = new APIPaing<List<Enterprise>>();
            var list = enterpriseRepository.GetAll().Result.Where(o => o.IsDelete == 0);
            result.TotalCount = list.Count();
            result.PageCount = (int)Math.Ceiling((double)result.TotalCount / request.PageSize);
            list = list.OrderByDescending(o => o.EnterpriseId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            var data = mapper.Map<List<Enterprise>>(list);
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            result.data = data;
            return await Task.FromResult(result);
        }
    }
}
